package com.cqhz.quwan.util

import java.util.*
import kotlin.collections.ArrayList

/**
 * 数字按照指定位数补零
 */
fun Int.slice(num:Int):String{
    return String.format("%0$num" + "d",this)
}

fun List<Int>.random(num:Int?):List<Int>?{
    val source = ArrayList<Int>()
    source.addAll(this)
    if(num == null){
        return null
    }
    val result = IntArray(num)
    val rd = Random()
    var index = 0
    var len = size
    for (i in result.indices) {
        //待选数组0到(len-2)随机一个下标
        index = Math.abs(rd.nextInt() % len--)
        //将随机到的数放入结果集
        result[i] = source[index]
        //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
        source[index] = source[len]
    }
    return result.toList()
}
fun IntRange.random(num:Int): IntArray{
    var len = last - first + 1

    //初始化给定范围的待选数组
    val source = IntArray(len)
    for (i in first until first + len) {
        source[i - first] = i
    }

    val result = IntArray(num)
    val rd = Random()
    var index = 0
    for (i in result.indices) {
        //待选数组0到(len-2)随机一个下标
        index = Math.abs(rd.nextInt() % len--)
        //将随机到的数放入结果集
        result[i] = source[index]
        //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
        source[index] = source[len]
    }
    return result
}
fun Double.format():String{
    return String.format("%.2f",this)
}


fun Int.combine(num:Int):Long{
    return if (this < num || num < 0) {
        0L
    } else factorial(this, this - num + 1) / factorial(num, 1)
}

private fun factorial(max: Int, min: Int): Long {
    return if (max >= min && max > 1) {
        max * factorial(max - 1, min)
    } else {
        1L
    }
}